package com.example.blog.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 保底统一返回值处理
 */
// 保底统一返回值处理
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    // Autowired注入ObjectMapper
    @Autowired
    private ObjectMapper objectMapper;
    // 标记返回值是否支持
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    // 对返回值进行处理
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 如果返回值是ResultAjax类型
        if(body instanceof ResultAjax){
            return body;
        }
        // 如果返回值是字符串类型
        if(body instanceof String){
            // 将body转换为ResultAjax类型
            ResultAjax resultAjax = ResultAjax.succ(body);
            try {
                // 将ResultAjax类型转换为字符串
                return objectMapper.writeValueAsString(resultAjax);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        // 将body转换为ResultAjax类型
        return ResultAjax.succ(body);
    }
}